import React, { useState, useEffect } from 'react';
import { 
  Container, 
  Box, 
  Typography, 
  Card, 
  CardContent, 
  Grid, 
  List, 
  ListItem, 
  ListItemText, 
  ListItemSecondaryAction, 
  Button, 
  Chip, 
  Dialog, 
  DialogTitle, 
  DialogContent, 
  DialogActions, 
  Alert,
  CircularProgress,
  IconButton,
  FormControl,
  InputLabel,
  Select,
  MenuItem
} from '@mui/material';
import { AdminPanelSettings, Person, Security } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { apiRequest } from '../utils/api';

const AdminDashboard = () => {
  const [users, setUsers] = useState([]);
  const [filteredUsers, setFilteredUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [selectedUser, setSelectedUser] = useState(null);
  const [roleDialogOpen, setRoleDialogOpen] = useState(false);
  const [updatingRole, setUpdatingRole] = useState(false);
  const [roleFilter, setRoleFilter] = useState('ALL');
  const navigate = useNavigate();

  useEffect(() => {
    fetchUsers();
  }, []);

  useEffect(() => {
    // 根据选择的角色筛选用户
    if (roleFilter === 'ALL') {
      setFilteredUsers(users);
    } else {
      setFilteredUsers(users.filter(user => user.role === roleFilter));
    }
  }, [users, roleFilter]);

  const fetchUsers = async () => {
    try {
        setLoading(true);
        setError('');
        console.log('开始获取用户列表...');
        
        // 检查token是否存在
        const token = localStorage.getItem('token');
        console.log('Token存在:', !!token);
        
        const response = await apiRequest.get('/api/users/admin/all');
        console.log('获取到的用户数据:', response.data);
        setUsers(response.data);
    } catch (err) {
        console.error('获取用户列表失败:', err);
        console.error('错误详情:', err.response?.data);
        console.error('状态码:', err.response?.status);
        
        let errorMessage = '获取用户列表失败';
        if (err.response?.status === 401) {
            errorMessage = '未授权访问，请先登录';
            // 清除无效token
            localStorage.removeItem('token');
            navigate('/login');
        } else if (err.response?.status === 403) {
            errorMessage = '权限不足，需要管理员权限。请联系系统管理员授权。';
            console.error('当前用户权限:', '需要ADMIN角色才能访问');
        } else if (err.response?.status === 404) {
            errorMessage = 'API接口未找到';
        } else if (!err.response) {
            errorMessage = '网络连接失败，请检查后端服务是否启动';
        }
        
        setError(errorMessage);
    } finally {
        setLoading(false);
    }
  };

  const handleRoleChange = async (userId, newRole) => {
    try {
      setUpdatingRole(true);
      await apiRequest.put(`/api/users/admin/${userId}/role`, { role: newRole });
      setRoleDialogOpen(false);
      fetchUsers(); // 重新获取用户列表
    } catch (err) {
      console.error('Error updating role:', err);
      setError('更新用户角色失败');
    } finally {
      setUpdatingRole(false);
    }
  };

  const getRoleColor = (role) => {
    switch (role) {
      case 'ADMIN':
        return 'error';
      case 'SERVICE_PROVIDER':
        return 'warning';
      default:
        return 'primary';
    }
  };

  const getRoleDisplayName = (role) => {
    switch (role) {
      case 'ADMIN':
        return '管理员';
      case 'SERVICE_PROVIDER':
        return '服务商';
      case 'USER':
        return '普通用户';
      default:
        return role;
    }
  };

  if (loading) {
    return (
      <Container maxWidth="lg" sx={{ mt: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 8 }}>
          <CircularProgress />
        </Box>
      </Container>
    );
  }

  return (
    <Container maxWidth="lg" sx={{ mt: 4 }}>
      <Box sx={{ mb: 4 }}>
        <Typography variant="h4" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <AdminPanelSettings color="primary" />
          管理员控制台
        </Typography>
        <Typography variant="body1" color="text.secondary">
          管理系统用户和权限
        </Typography>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError('')}>
          {error}
        </Alert>
      )}

      <Grid container spacing={3}>
        <Grid item xs={12} md={8}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Person />
                  用户列表
                </Typography>
                <FormControl size="small" sx={{ minWidth: 120 }}>
                  <InputLabel>用户类型</InputLabel>
                  <Select
                    value={roleFilter}
                    onChange={(e) => setRoleFilter(e.target.value)}
                    label="用户类型"
                  >
                    <MenuItem value="ALL">全部用户</MenuItem>
                    <MenuItem value="ADMIN">管理员</MenuItem>
                    <MenuItem value="USER">普通用户</MenuItem>
                    <MenuItem value="SERVICE_PROVIDER">服务商</MenuItem>
                  </Select>
                </FormControl>
              </Box>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                共 {filteredUsers.length} 个用户
                {roleFilter !== 'ALL' && `（${roleFilter === 'ADMIN' ? '管理员' : roleFilter === 'USER' ? '普通用户' : '服务商'}）`}
              </Typography>
              
              <List>
                {filteredUsers.map((user) => (
                  <ListItem key={user.id} divider sx={{ px: 2, py: 2 }}>
                    <ListItemText
                      primary={
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
                          <Typography variant="subtitle1" sx={{ fontWeight: 'medium' }}>
                            {user.firstName} {user.lastName}
                          </Typography>
                          <Chip 
                            label={getRoleDisplayName(user.role)} 
                            color={getRoleColor(user.role)}
                            size="small"
                            variant="outlined"
                          />
                        </Box>
                      }
                      secondary={
                        <Box sx={{ mt: 1 }}>
                          <Typography variant="body2" color="text.secondary" gutterBottom>
                            {user.email}
                          </Typography>
                          <Typography variant="body2" color="text.secondary">
                            车辆: {user.vehicleIds && user.vehicleIds.length > 0 ? user.vehicleIds.join(', ') : '未绑定'}
                          </Typography>
                        </Box>
                      }
                      sx={{ pr: 2 }}
                    />
                    <Box sx={{ ml: 1 }}>
                      <Button
                        variant="outlined"
                        size="small"
                        onClick={() => {
                          setSelectedUser(user);
                          setRoleDialogOpen(true);
                        }}
                        startIcon={<Security />}
                        sx={{ whiteSpace: 'nowrap' }}
                      >
                        修改角色
                      </Button>
                    </Box>
                  </ListItem>
                ))}
              </List>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={4}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                <Typography variant="h6" gutterBottom>
                  统计信息
                </Typography>
                <Typography variant="caption" color="text.secondary" sx={{ textAlign: 'right' }}>
                  实时统计
                </Typography>
              </Box>
              <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, alignItems: 'flex-end' }}>
                <Typography variant="body2" color="text.secondary">
                  管理员: <strong>{users.filter(u => u.role === 'ADMIN').length}</strong> 人
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  普通用户: <strong>{users.filter(u => u.role === 'USER').length}</strong> 人
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  服务商: <strong>{users.filter(u => u.role === 'SERVICE_PROVIDER').length}</strong> 人
                </Typography>
                <Typography variant="body2" color="text.secondary" sx={{ mt: 1, pt: 1, borderTop: '1px solid', borderColor: 'divider' }}>
                  已绑定车辆: <strong>{users.filter(u => u.vehicleIds && u.vehicleIds.length > 0).length}</strong> 辆
                </Typography>
              </Box>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* 角色修改对话框 */}
      <Dialog open={roleDialogOpen} onClose={() => setRoleDialogOpen(false)}>
        <DialogTitle>修改用户角色</DialogTitle>
        <DialogContent>
          <Typography variant="body1" gutterBottom>
            为 {selectedUser?.firstName} {selectedUser?.lastName} ({selectedUser?.email}) 选择新角色：
          </Typography>
          <Box sx={{ mt: 2 }}>
            <Button
                variant={selectedUser?.role === 'ADMIN' ? 'contained' : 'outlined'}
                color="error"
                onClick={() => handleRoleChange(selectedUser?.id, 'ADMIN')}
                disabled={updatingRole}
                sx={{ mr: 1 }}
              >
                管理员
              </Button>
              <Button
                variant={selectedUser?.role === 'SERVICE_PROVIDER' ? 'contained' : 'outlined'}
                color="warning"
                onClick={() => handleRoleChange(selectedUser?.id, 'SERVICE_PROVIDER')}
                disabled={updatingRole}
                sx={{ mr: 1 }}
              >
                服务商
              </Button>
              <Button
                variant={selectedUser?.role === 'USER' ? 'contained' : 'outlined'}
                color="primary"
                onClick={() => handleRoleChange(selectedUser?.id, 'USER')}
                disabled={updatingRole}
              >
                普通用户
              </Button>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRoleDialogOpen(false)} disabled={updatingRole}>
            取消
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default AdminDashboard;